package com.knowledge.plus.other.下载文件;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * 从服务器下载文件
 *
 * @author TPF
 * @since 2025/8/21
 */
@Slf4j
@Controller
@RequestMapping("file")
public class DownloadDemo {

    @GetMapping("/down")
    public void fileDownload(HttpServletResponse response) {
        try {
            Map<String, String> map = new HashMap<>();
            map.put("file-path", "/usr/local/nginx/html/image1.png");   // 文件的绝对路径
            map.put("file-name", "image1.png");     // 文件名称（带后缀）
            map.put("file-suffix", ".png");     // 文件后缀


            String fileAddress = map.get("file-path");
            File file = new File(fileAddress);
            if (!file.exists()) {
                response.sendError(HttpServletResponse.SC_NOT_FOUND, "文件不存在");
                return;
            }

            response.reset();
            // CORS 配置
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Content-Length, X-Requested-With");
            response.setHeader("Content-Disposition", "attachment;fileName=\"" + map.get("file-name") + "\"");
            response.setContentType(getContentType(map.get("file-suffix")));
            response.setContentLengthLong(file.length());

            // 文件下载
            InputStream in = new BufferedInputStream(new FileInputStream(file));
            FileCopyUtils.copy(in, response.getOutputStream());
        } catch (IOException e) {
            log.error("文件下载失败", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载失败");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        } catch (Exception e) {
            log.error("文件下载异常", e);
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "下载异常");
            } catch (IOException ex) {
                log.error("发送错误响应失败", ex);
            }
        }

    }

    private String getContentType(String fileSuffix) {
        if (fileSuffix == null) {
            return "application/octet-stream";
        }
        switch (fileSuffix.toLowerCase()) {
            case "jpg":
            case "jpeg":
                return "image/jpeg";
            case "png":
                return "image/png";
            case "gif":
                return "image/gif";
            case "mp4":
                return "video/mp4";
            case "pdf":
                return "application/pdf";
            case "doc":
                return "application/msword";
            case "docx":
                return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
            case "xls":
                return "application/vnd.ms-excel";
            case "xlsx":
                return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            default:
                return "application/octet-stream";
        }
    }



}
